package tgc.tdu.tgq.demo.web.controller;

import java.util.HashSet;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.tdu.tgq.demo.custom.BaseController;
import tgc.tdu.tgq.demo.entity.TbClass;
import tgc.tdu.tgq.demo.service.TbClassService;
import tgc.tdu.tgq.demo.web.form.TbClassForm;

@Controller
@RequestMapping(value = "/banji")
public class TbClassController extends BaseController<TbClass, Integer, TbClassForm>{
	@Autowired
	private TbClassService TbClassService;
	
	@Override
	public Specification<TbClass> buildSpec(TbClassForm form) {
		@SuppressWarnings("serial")
		Specification<TbClass> spec=new Specification<TbClass>() {

			@Override
			public Predicate toPredicate(Root<TbClass> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				String name = form.getName();
				if(StringUtils.hasText(name)) {
					rules.add(cb.like(root.get("name"), "%"+name+"%"));
				}
				String manager = form.getManager();
				if(StringUtils.hasText(manager)) {
					rules.add(cb.like(root.get("manager"), "%"+manager+"%"));
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;
	}
	@RequestMapping(value = "/bj",method = RequestMethod.POST)
	@ResponseBody
	public Object bj(TbClassForm form) {
		Specification<TbClass> spec=buildSpec(form);
		return TbClassService.findAll(spec);
	}
	
	@RequestMapping(value = "/all")
	@ResponseBody
	public Object all() {
		List<TbClass> list=TbClassService.findAll();
		return list;
	}
}
